package com.example.github.jdbc;

import com.example.github.jdbc.entity.Person;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class JDBCDML {
    public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://127.0.0.1:3306/lc-cc";
        String username = "root";
        String password = "123456";
        // 创建连接
        Connection connection = DriverManager.getConnection(url, username, password);
        String selectSql = "select id, name, email from person";
        // 预编译执行查询的sql
        PreparedStatement preparedStatement = connection.prepareStatement(selectSql);
        ResultSet resultSet = preparedStatement.executeQuery();
        Person person = null;
        List<Person> personList = new ArrayList<>();
        // 遍历字段输出
        while (resultSet.next()) {
            person = new Person();
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            String email = resultSet.getString("email");
            person.setId(id);
            person.setName(name);
            person.setEmail(email);
            personList.add(person);
        }
        System.out.println(personList);
        // 从内到外关闭连接
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}
